package com.muyu.cloud.commodity.service.imp;

import com.muyu.cloud.commodity.domain.model.Category;
import com.muyu.cloud.commodity.domain.req.CategoryAddReq;
import com.muyu.cloud.commodity.domain.req.CategoryUpdDateReq;
import com.muyu.cloud.commodity.mapper.CategoryMapper;
import com.muyu.cloud.commodity.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

  @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> listByParentId(Long parentId) {
        return categoryMapper.listByParentId(parentId);
    }
    /**
     * 分类树
     * @return
     */
    @Override
    public List<Category> tree() {
        List<Category> all = categoryMapper.selectAll();
        Map<Long, List<Category>> parentIdToChildren = all.stream()
                .collect(Collectors.groupingBy(c -> Optional.ofNullable(c.getParentId()).orElse(0L)));
        List<Category> roots = parentIdToChildren.getOrDefault(0L, Collections.emptyList());
        attachChildrenRecursively(roots, parentIdToChildren);
        return roots;
    }

    private void attachChildrenRecursively(List<Category> nodes, Map<Long, List<Category>> parentIdToChildren) {
        if (nodes == null || nodes.isEmpty()) return;
        for (Category node : nodes) {
            List<Category> children = parentIdToChildren.getOrDefault(node.getId(), Collections.emptyList());

            try {
                java.lang.reflect.Field f = Category.class.getDeclaredField("children");
                f.setAccessible(true);
                f.set(node, children);
            } catch (Exception ignored) {}
            attachChildrenRecursively(children, parentIdToChildren);
        }
    }

    /**
     * 分类添加
     * @param req
     */
    @Override
    public void addCategory(CategoryAddReq req) {
        // 计算层级
        //(给一个默认值唯一)
        //先判断是否有父级id
        Integer level = 1;
        if (req.getParentId() != null && req.getParentId() > 0) {
            //如果有的话进行查询id
            Category parent = categoryMapper.selectById(req.getParentId());
            if (parent != null) {
                //在他父类id上加一
                level = parent.getLevel() + 1;
            }
        }

        // 构建分类对象
        Category category = new Category();
        category.setCategoryName(req.getCategoryName());
        category.setParentId(req.getParentId() != null ? req.getParentId() : 0L);
        category.setCategoryIcon(req.getCategoryIcon());
        category.setLevel(level);
        category.setSort(req.getSort());
        category.setStatus(req.getStatus() != null ? req.getStatus() : 1);

        // 添加分类
        categoryMapper.insert(category);
    }

    /**
     * 修改分类
     * @param categoryUpdDateReq
     */
    @Override
    public void update(CategoryUpdDateReq categoryUpdDateReq) {

        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdDateReq,category);
        //修改分类
        categoryMapper.update(category);

    }
}